package dennis;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class FileIO {
	public static boolean SaveXML(String ddmmyy, String start, String due, String labelname, boolean impt, String task) {
		try {
			 
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
	 
			// root elements
			Document doc = docBuilder.newDocument();
			Element rootElement = doc.createElement("Jim");
			doc.appendChild(rootElement);
	 
			// staff elements
			Element item = doc.createElement("Item");
			rootElement.appendChild(item);
	 
			// set attribute to staff element
			Attr attr = doc.createAttribute("id");
			attr.setValue("1");
			item.setAttributeNode(attr);
	 
			// shorten way
			// staff.setAttribute("id", "1");
	 
			Element Label = doc.createElement("Label");
			Label.appendChild(doc.createTextNode(labelname));
			item.appendChild(Label);
				 
			Element TaskDescription = doc.createElement("Task");
			TaskDescription.appendChild(doc.createTextNode(task)); 
			item.appendChild(TaskDescription);
	 
			Element Date = doc.createElement("Date");
			Date.appendChild(doc.createTextNode(ddmmyy));
			item.appendChild(Date);
			
			Element StartTime = doc.createElement("StartTime");
			StartTime.appendChild(doc.createTextNode(start));
			item.appendChild(StartTime);
		
			Element DueTime = doc.createElement("DueTime");
			DueTime.appendChild(doc.createTextNode(due));
			item.appendChild(DueTime);
			
			Element Importance = doc.createElement("Importance");
			if(impt)
				Importance.appendChild(doc.createTextNode("YES"));
			else
				Importance.appendChild(doc.createTextNode("NO"));
			item.appendChild(Importance);
			
			// write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File("file.xml"));
	 
			// Output to console for testing
			// StreamResult result = new StreamResult(System.out);
	 
			transformer.transform(source, result);
	 
			//System.out.println("Dennis-<File saved!");
	 
		  } catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		  } catch (TransformerException tfe) {
			tfe.printStackTrace();
		  }
		return true;
	}

}
